package com.dao;

import com.util.DBUtil;
import com.entity.Type;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TypeInfo implements TypeDao{



    @Override
    public List<Type> typeSelectAll() throws SQLException {
        Connection conn = DBUtil.getConn();
        String sql = "select * from type_table ";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        List<Type> typeList = new ArrayList<Type>();
        while (rs.next()){
            Integer t_id = rs.getInt("t_id");
            String t_name = rs.getString("t_name");
            typeList.add(new Type(t_id,t_name));
        }
        DBUtil.close(rs,ps,conn);
        return typeList;
    }

    @Override
    public Type typeSelectOne(Integer t_id) throws SQLException {
        Connection conn = DBUtil.getConn();
        String sql = "select * from type_table where t_id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,t_id);
        ResultSet rs = ps.executeQuery();
        String t_name = rs.getString("t_name");
        Type type = new Type(t_id, t_name);
        System.out.println("获取成功"+type.toString());
        DBUtil.close(rs,ps,conn);
        return type;
    }

    @Override
    public boolean insertType(String t_name) throws SQLException {
        Connection conn = DBUtil.getConn();
        String sql = "insert into type_table (t_name) values (?)";
        PreparedStatement ps = conn.prepareStatement(sql);
//        ResultSet rs = ps.executeQuery();
        ps.setString(1,t_name);
        int result = ps.executeUpdate();
        DBUtil.close(null,ps,conn);
        return result > 0;
    }

    @Override
    public boolean updateType(Integer t_id, String t_name) throws SQLException {
        Connection conn = DBUtil.getConn();
        String sql = "update type_table set t_name=? where t_id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
//        ResultSet rs = ps.executeQuery();
        ps.setString(1,t_name );
        ps.setInt(2,t_id );
        int result = ps.executeUpdate();
        System.out.println(result);
        DBUtil.close(null,ps,conn);
        return result > 0;
    }

    @Override
    public boolean deleteType(Integer t_id) throws SQLException {
        Connection conn = DBUtil.getConn();
        String sql = "delete from  type_table where t_id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
//        ResultSet rs = ps.executeQuery();
        ps.setInt(1,t_id);
        int result = ps.executeUpdate();
        DBUtil.close(null,ps,conn);
        return result > 0;
    }
}
